package com.vm.activity;

import java.io.File;

import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.vm.commons.StringUtil;
import com.vm.commons.VMConst;
import com.vm.db.DownInfoDao;
import com.vm.model.Soft;
import com.vm.utils.ApkUtils;
import com.vm.utils.DownloadThread;
import com.vm.utils.JsonUtils;
import com.vm.utils.MyVolley;
import com.vm.utils.ThreadManager;
import com.wwtscapp.apk.R;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @ProjectName: [WeiMai]
 * @Author: [kent.wang]
 * @CreateDate: [2015年3月10日 下午6:04:56]
 * @Version: [v1.0]
 * 
 */
public class AboutAcitivity extends Activity {

	private DownloadThread downThread;
	private Handler downHandler;

	RequestQueue mQueue;
	ImageView imgbtn_search_back;
	TextView tv_user_agreement;
	TextView tv_software_versions;
	TextView tv_now_version;
	TextView tv_version;
	LinearLayout llayout_user_agreement;
	LinearLayout llayout_about_us;
	Soft soft;
	String versionName;
	LinearLayout rlayout_update;
	DownInfoDao dao;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.about);

		mQueue = MyVolley.getRequestQueue();
		dao = new DownInfoDao(this);
		init();
	}

	/**
	 * 初始化
	 */
	private void init() {
		llayout_user_agreement = (LinearLayout) findViewById(R.id.llayout_user_agreement);
		llayout_about_us = (LinearLayout) findViewById(R.id.llayout_about_us);
		imgbtn_search_back = (ImageView) findViewById(R.id.imgbtn_search_back);
		imgbtn_search_back.setOnClickListener(btn_backListener);
		tv_version = (TextView) findViewById(R.id.tv_version);
		tv_user_agreement = (TextView) findViewById(R.id.tv_user_agreement);

		llayout_user_agreement.setOnClickListener(agreementClickListener);
		llayout_about_us.setOnClickListener(aboutClickListener);
		rlayout_update = (LinearLayout) findViewById(R.id.rlayout_update);

		tv_now_version = (TextView) findViewById(R.id.tv_now_version);
		tv_software_versions = (TextView) findViewById(R.id.tv_software_versions);

		getVersion();
		getNewVersion();
	}

	public void getNewVersion() {
		String url = VMConst.DETAIL_URL
				+ "96f480a8-6911-46f0-a92f-11ea4a42304e";

		if (downThread != null) {
			return;
		}

		JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null,
				new Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {

						soft = JsonUtils.jsonToBean(arg0, Soft.class);

						if (!versionName.equals(soft.getVersion())) {
							tv_version.setVisibility(View.GONE);
							tv_now_version.setVisibility(View.VISIBLE);
							rlayout_update
									.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View v) {
											tv_now_version.setEnabled(false);
											Toast toast2 = Toast.makeText(
													AboutAcitivity.this,
													"下载更新文件", 1000);
											toast2.setGravity(Gravity.CENTER,
													0, 0);
											toast2.show();
											Message msg = new Message();
											// msg.arg1 = currentId;
											msg.what = 100;
											// 下载地址
											// msg.obj = VMConst.DOWN_URL +
											// currentId + "&userId="
											// + CurrentUser.USERID;
											try {
												File file = new File(
														Environment
																.getExternalStorageDirectory()
																.getPath()
																+ "/vmclient/"
																+ soft.getName()
																+ ".apk");
												// deleteFile(file);
												// dao.delete(path, softId);
												dao.delete(
														file.getAbsolutePath(),
														soft.getId());
												ApkUtils.deleteFile(file);
											} catch (Exception e) {
												// TODO Auto-generated catch
												// block
												e.printStackTrace();
											}

											msg.obj = soft;
											downThread = ThreadManager.getDownloadThread(
													AboutAcitivity.this
															.getApplicationContext(),
													soft.getId(), mainHandler);

											do {
												downHandler = downThread
														.getDownHandler();
											} while (null == downHandler);

											downHandler.sendMessage(msg);
										}
									});
						} else {
							tv_version.setVisibility(View.VISIBLE);
							tv_now_version.setVisibility(View.GONE);
						}
					}
				}, null);
		mQueue.add(jsonObjectRequest);
	}

	public void getVersion() {
		try {
			PackageManager manager = this.getPackageManager();
			PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
			versionName = info.versionName;
			tv_software_versions.setText("" + versionName);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private Handler mainHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1000:

				dao.complete("96f480a8-6911-46f0-a92f-11ea4a42304e");
				File apkfile = new File(StringUtil.getSdApkUrl(soft.getName()));
				if (!apkfile.exists()) {
					return;
				}
				Intent i = new Intent(Intent.ACTION_VIEW);

				i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
						"application/vnd.android.package-archive");
				AboutAcitivity.this.startActivity(i);

				break;
			default:
				break;
			}
			super.handleMessage(msg);

		}
	};
	OnClickListener aboutClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(AboutAcitivity.this,
					AboutUsActivity.class);
			startActivity(intent);
		}
	};
	OnClickListener agreementClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(AboutAcitivity.this,
					AgreementActivity.class);
			startActivity(intent);
		}
	};

	/**
	 * imgbtn_search_back 返回按钮监听
	 */
	OnClickListener btn_backListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			onBackPressed();
		}
	};

	/**
	 * 手机自带返回按钮监听
	 */
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

}
